package util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisUtil {

	@Autowired
	private JedisPool jedisPool;
	
	
	public String get(String key){
		Jedis jedis=jedisPool.getResource();
		String value= jedis.get(key);
		close(jedis);
		return value;
	}
	
	public boolean set(String key,String value){
		Jedis jedis=jedisPool.getResource();
		try {
			jedis.set(key, value);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return false;
		}
		close(jedis);
		return true;
	}
	
	public void del(String ...keys){
		Jedis jedis=jedisPool.getResource();
		jedis.del(keys);
		close(jedis);
	}
	
	public Set<String> getvalues(String pattern){
		Jedis jedis=jedisPool.getResource();
		Set<String> values= jedis.keys(pattern);
		close(jedis);
		return values;
	}
	
	public boolean exists(String key){
		Jedis jedis=jedisPool.getResource();
		boolean b= jedis.exists(key);
		close(jedis);		
		return b;
	}
	
	public boolean expire(String key,int seconds){
		Jedis jedis=jedisPool.getResource();
		Long i=jedis.expire(key, seconds);
		close(jedis);
		return i!=0;
	}
	
	public boolean hset(String key, String field,String value){
		Jedis jedis=jedisPool.getResource();
		Long i=jedis.hset(key, field, value);
		close(jedis);
		return i!=0;
	}
	
	public String hget(String key,String field){
		Jedis jedis=jedisPool.getResource();
		String value= jedis.hget(key, field);
		close(jedis);
		return value;
	} 
	
	public boolean hmset (String key,HashMap<String,String> hash){
		Jedis jedis=jedisPool.getResource();
		try {
			jedis.hmset(key, hash);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return false;
		}
		close(jedis);
		return true;
	}
	
	public List<String> hmget (String key,String ...fields){
		Jedis jedis=jedisPool.getResource();
		List<String> values=jedis.hmget(key, fields);
		return values;
	}
	
	public boolean lpush(String key,String ...strings){
		Jedis jedis=jedisPool.getResource();
		Long i=jedis.lpush(key, strings);
		close(jedis);
		return i!=0;
	}
	
	
	public void close(Jedis jedis){
		if(null!=jedis){
			jedis.close();
		}
	}
	
	public void returnResource(Jedis jedis){
		jedisPool.returnResource(jedis);
	}
	
	public void returnBrokenResource(Jedis jedis){
		jedisPool.returnBrokenResource(jedis);
	}
	
	
	
}
